package controller

import (
	"appService/src/application"
	"appService/src/application/app/appModels"
	"appService/src/authValid"
	"appService/src/global"
	"appService/src/orm"
	"errors"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gfile"
	"os"
	"path/filepath"
	"time"
	"xorm.io/builder"
	"xorm.io/xorm"
)

type Files struct {
	application.BaseController
}
//getModel 获取控制器对应的 模型
func  (*Files)getModel() appModels.IModel{
	return new(appModels.Files)
}
//Get 获取一条数据
func (this *Files) Get(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.GetEx(func(db *xorm.Session, id string) error {
		file := req.Model.(*appModels.Files)
		_, err := authValid.FolderIdGetFolder(file.FolderId, req.LoginUser, "文件", file.FileName)
		if err != nil {
			return err
		}
		db.Where(builder.Eq{"id": id})
		return nil
	})
}

//Add 添加
func (this *Files) Add(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	folderId := r.GetString("folder_id", "")
	if folderId == "" {
		req.JsonError("请选择要文件要上传到的文件夹")
	}
	_, err := authValid.FolderIdGetFolder(folderId, req.LoginUser)
	if err != nil {
		req.JsonErrorf("%v", err)
	}
	file := (*appModels.Files)(nil)
	err = orm.Transaction("文件上传", func(db *xorm.Session) error {
		temFile := req.UploadFile("upload-file")
		temFile.FolderId = folderId
		err := temFile.AddValid()
		if err != nil {
			return err
		}
		_, err = db.Insert(temFile)
		if err != nil {
			g.Log().Errorf("插入文件信息，错误：%v", err)
			err = os.RemoveAll(filepath.Join(global.FileRootDir, temFile.FileUrl))
			if err != nil {
				g.Log().Errorf("删除文件【%v】，错误：%v", temFile.FileUrl, err)
			}
			return errors.New("上传文件失败")
		}
		file = temFile
		return nil
	}, func() {
		err = os.RemoveAll(filepath.Join(global.FileRootDir, file.FileUrl))
		if err != nil {
			g.Log().Errorf("删除文件【%v】，错误：%v", file.FileUrl, err)
		}
	})
	if err != nil {
		req.JsonErrorf("%v", err)
	}
	file.FileUrl = ""
	req.JsonSuccessData(file)
}

//Delete 删除
func (this *Files) Delete(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	delFiles := make([]appModels.Files, 0)
	req.DeleteEx(func(db *xorm.Session, ids ...string) error {
		for _, id := range ids {
			file := new(appModels.Files)
			ok, err := orm.Db.Where(builder.Eq{"id": id}).Get(file)
			if err != nil {
				g.Log().Errorf("查询文件失败，错误：%v", err)
				return errors.New("删除失败")
			}
			if !ok {
				return errors.New("文件不存在")
			}
			_, err = authValid.FolderIdGetFolder(file.FolderId, req.LoginUser, "文件", file.FileName)
			if err != nil {
				return err
			}
			delFiles = append(delFiles, *file)
		}
		db.Where(builder.In("id", ids))
		return nil
	}, func() {
		for _, f := range delFiles {
			fPath := filepath.Join(global.FileRootDir, f.FileUrl)
			err := gfile.Remove(fPath)
			if err != nil {
				g.Log().Errorf("删除文件：%v ，路径：%v ===> 失败，错误：%v", f.FileName, fPath, err)
			}
		}
	})
}

//Edit 修改
/*
func (this *Files) Edit(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.EditEx(func(db *xorm.Session) error {
		return req.Model.EditValid()
	}, func(db *xorm.Session) error {
		file := req.Model.(*appModels.Files)
		if file.Id == "" {
			return errors.New("请选择要修改的数据")
		}
		_, err := authValid.FolderIdGetFolder(file.FolderId, req.LoginUser, "文件", file.FileName)
		if err != nil {
			return err
		}
		db.Where(builder.Eq{"id": file.Id})
		return nil
	})
}
*/

//ListPaginate 获取列表（分页）
func (this *Files) ListPaginate(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.ListPaginateEx(func() (slice interface{}, table interface{}) {
		slice = new([]struct {
			Id       string    `json:"id"`        //id guid
			Bid      string    `json:"bid"`       //所属单位ID branch表的ID
			FolderId string    `json:"folder_id"` //所属文件夹ID
			FileSign string    `json:"file_sign"` // 文件下载获取时使用的唯一sign
			FileName string    `json:"file_name"` //文件名称
			FileSize int64     `json:"file_size"` //文件大小
			FileExt  string    `json:"file_ext"`  //文件后缀名
			Created  time.Time `json:"created"`   //上传时间
		})
		table = req.Model.Model()
		return
	}, func(db *xorm.Session) error {
		return nil
	}, func(db *xorm.Session) error {
		file := req.Model.(*appModels.Files)
		if file.FolderId == "" {
			ids := authValid.GetAllUserFolderIds(req.LoginUser)
			db.Where(builder.In("folder_id", *ids))
		} else {
			ids := authValid.GetUserFolderAllChildren(file.FolderId, req.LoginUser)
			db.Where(builder.In("folder_id", *ids))
		}
		return nil
	})
}
